From 903baafa5b6e16a2d8fe5f8f21588c22a3386c63 Mon Sep 17 00:00:00 2001
From: Vladislav Tarakanov <vladislav.tarakanov@bk.ru>
Date: Thu, 21 Mar 2024 13:39:20 +0400
Subject: [PATCH 6/6] Fix "Pages per Sheet" margin error

Change-Id: I37ec1c1c5a612937cb638594d8df590a2d97b98f
---
 vcl/source/window/printdlg.cxx | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/vcl/source/window/printdlg.cxx b/vcl/source/window/printdlg.cxx
index cc2cf09d44e9..327e923f45e8 100644
--- a/vcl/source/window/printdlg.cxx
+++ b/vcl/source/window/printdlg.cxx
@@ -1395,7 +1395,24 @@ void PrintDialog::updateNupFromPages( bool i_bMayUseCache )
     if( nPages > 1 )
     {
         // set upper limits for margins based on job page size and rows/columns
+        VclPtr<Printer> aPrt( maPController->getPrinter() );
         Size aSize( getJobPageSize() );
+        // Use printer defined paper size
+        if (aPrt->GetPaperInfoCount() > mxPaperSizeBox->get_active())
+        {
+            PaperInfo aPaperInfo = aPrt->GetPaperInfo( mxPaperSizeBox->get_active() );
+            aSize = Size(aPaperInfo.getWidth(), aPaperInfo.getHeight());
+        }
+        // Use user defined paper size
+        else if (aPrt->GetPaperInfoCount() <= mxPaperSizeBox->get_count())
+        {
+            Size originalSize = getJobPageSize();
+            if ( (aSize.getWidth() > aSize.getHeight() && originalSize.Width() < originalSize.Height())
+              || (aSize.getWidth() < aSize.getHeight() && originalSize.Width() > originalSize.Height()) )
+            {
+                aSize = Size(aSize.getHeight(), aSize.getWidth());
+            }
+        }
 
         // maximum sheet distance: 1/2 sheet
         tools::Long nHorzMax = aSize.Width()/2;
-- 
2.40.1

